package logic

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"pharymacy-management-system/dao/mysql"
	"pharymacy-management-system/models"
	"pharymacy-management-system/network"
	"pharymacy-management-system/pkg/snowflake"
	"strconv"
)

func GetAllVip(c *gin.Context) {
	vipList, err := mysql.SelectAllVip()
	if err != nil {
		zap.L().Error("mysql.SelectAllVip() failed", zap.Error(err))
		network.ResponseError(c, network.CodeServerBusy)
		return
	}
	data := map[string]interface{}{}
	data["vipList"] = vipList
	network.ResponseSuccess(c, data)
}

func AddVip(c *gin.Context) {
	var userID int64
	temp := c.Param("userID")
	userID, err := strconv.ParseInt(temp, 10, 64)
	if err != nil {
		zap.L().Error("strconv.ParseInt(c.PostForm(\"userID\")) failed", zap.Error(err))
		network.ResponseError(c, network.CodeInvalidParam)
		return
	}
	user, err := mysql.SelectByUserID(userID)
	if err != nil {
		zap.L().Error("mysql.SelectByUserID(userID) failed", zap.Error(err))
		network.ResponseError(c, network.CodeServerBusy)
		return
	}
	if user != nil {
		zap.L().Error("user already exists", zap.Error(err))
		network.ResponseError(c, network.CodeInvalidParam)
		return
	}
	vipID := snowflake.GenID()
	vip := &models.Vip{
		VipID:    vipID,
		UserID:   userID,
		Integral: 0,
	}
	err = mysql.CreateVip(vip)
	if err != nil {
		zap.L().Error("mysql.CreateVip(vip) failed", zap.Error(err))
		network.ResponseError(c, network.CodeServerBusy)
		return
	}
	data := map[string]interface{}{}
	data["vip"] = vip
	network.ResponseSuccess(c, nil)
}

func UpdateVip(c *gin.Context) {
	var userID int64
	var number int
	var description string
	userID, err := strconv.ParseInt(c.Param("userID"), 10, 64)
	if err != nil {
		zap.L().Error("strconv.ParseInt(c.PostForm(\"userID\")) failed", zap.Error(err))
		network.ResponseError(c, network.CodeInvalidParam)
		return
	}
	number, err = strconv.Atoi(c.Param("number"))
	if err != nil {
		zap.L().Error("strconv.Atoi(c.PostForm(\"number\")) failed", zap.Error(err))
		network.ResponseError(c, network.CodeInvalidParam)
		return
	}
	description = c.Param("description")
	err = mysql.UpdateVip(userID, number, description)
	if err != nil {
		zap.L().Error("mysql.UpdateVip(userID, number) failed", zap.Error(err))
		network.ResponseError(c, network.CodeServerBusy)
		return
	}
	network.ResponseSuccess(c, nil)
}

func GetVipHistoryListByVipID(c *gin.Context) {
	var vipID int64
	vipID, err := strconv.ParseInt(c.Param("vipID"), 10, 64)
	if err != nil {
		zap.L().Error("strconv.ParseInt(c.Query(\"vipID\")) failed", zap.Error(err))
		network.ResponseError(c, network.CodeInvalidParam)
		return
	}
	vipHistoryList, err := mysql.GetVipHistoryListByVipID(vipID)
	if err != nil {
		zap.L().Error("mysql.GetVipHistoryListByVipID(vipID) failed", zap.Error(err))
		network.ResponseError(c, network.CodeServerBusy)
		return
	}
	data := map[string]interface{}{}
	data["vipHistoryList"] = vipHistoryList
	network.ResponseSuccess(c, data)
}
